package com.codeyang.config;

import com.codeyang.constant.GatewayConstant;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.List;

/**
 * 描述: jwt的过滤校验器
 *
 * @author CodeYang_Site
 * @version 2021/5/22 19:06
 */
@Component
public class JWTCheckFilter implements GlobalFilter, Ordered {

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 1.拿到request
     * 2.拿到路径
     * 3.拿到header
     * 4.拿到jwt
     *
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1
        ServerHttpRequest request = exchange.getRequest();
        //2
        String path = request.getURI().getPath();
        //3 放行白名单
        if (GatewayConstant.ALLOW_PATH.contains(path)) {
            //放行
            return chain.filter(exchange);
        }
        //不放行就检查token
        HttpHeaders headers = request.getHeaders();
        //4拿到jwt的信息
        List<String> auths = headers.get(GatewayConstant.AUTHORIZATION);
        if (!CollectionUtils.isEmpty(auths)) {
            String auth = auths.get(0);

            if (StringUtils.hasText(auth)) {
                //分割 token 注意有空格
                String jwt = auth.replaceAll("bearer ", "");
                //判断校验是否通过 redis中是否存在
                if (StringUtils.hasText(jwt) && redisTemplate.hasKey(GatewayConstant.OAUTH_JWT_PREFIX + jwt)) {
                    //放行
                    return chain.filter(exchange);
                }
            }
        }
        //不是放行的url 也没有正常的token 拦截放回401
        ServerHttpResponse response = exchange.getResponse();
        response.getHeaders().add("content-type", "application/json;charset=utf-8");
        HashMap<String, Object> map = new HashMap<>();
        map.put("code", 401);
        map.put("msg", "未授权");
        //写出去
        ObjectMapper objectMapper = new ObjectMapper();
        byte[] bytes = new byte[0];
        try {
            bytes = objectMapper.writeValueAsBytes(map);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        // 使用buffer工厂写出去
        DataBufferFactory dataBufferFactory = response.bufferFactory();
        DataBuffer wrap = dataBufferFactory.wrap(bytes);
        return response.writeWith(Mono.just(wrap));
    }

    /**
     * 数字越小 Filter等级越高
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
